//
//  WeChatLoginFlow.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/20.
//

import Combine

// 微信登陆流程
final class WeChatLoginFlow {
    private var wechatAuthStep:      WechatAuthStep!      // 第一步，调用wechat sdk 获取授权信息
    private let cdWechatLoginStep:   CDWechatLoginStep   //         第二步，调用凯度云接口使用微信返回的token登录，若返回10012错误码，则进入绑定登录流程bindLoginFlow（viewmodel中操作）
    
    private let cdGetUserInfoStep: CDGetUserLoginInfoStep    // 第三步，调用凯度云服务获取用户信息
    private let tuyaLoginPwdStep: TuyaLoginPwdStep      // 第四步，调用涂鸦的账号密码登录

    init() {
        cdWechatLoginStep = CDWechatLoginStep()
        tuyaLoginPwdStep = TuyaLoginPwdStep()
        cdGetUserInfoStep = CDGetUserLoginInfoStep()
        wechatAuthStep = WechatAuthStep()
    }
    
    func start() -> AnyPublisher<Void, Error> {
        wechatAuthStep =  WechatAuthStep() // 这里之所以重新创建授权step实体，主要是因为要重置其中的subject，防止多次触发。
        return wechatAuthStep.execute(.init())
            .flatMap { [weak self] authResult -> AnyPublisher<AuthAPI.WechatLogin.Response, Error> in
                return self?.cdWechatLoginStep.execute(.init(socialCode: authResult.socialCode, socialState: authResult.socialState)) ?? Fail(error: FlowError.stepMissing).eraseToAnyPublisher()
            }
            .flatMap { [weak self] response -> AnyPublisher<AuthAPI.UserLogInInfo.Response, Error> in
                AuthManager.shared.saveToken(response.access_token)
                return self?.cdGetUserInfoStep.execute(.init()) ?? Fail(error: FlowError.stepMissing).eraseToAnyPublisher()
            }
            .flatMap { [weak self] userInfo -> AnyPublisher<Void, Error> in
                return self?.tuyaLoginPwdStep.execute(.init(account:  userInfo.userName, password: userInfo.password)) ?? Fail(error: FlowError.stepMissing).eraseToAnyPublisher()
            }
            .eraseToAnyPublisher()
    }
    
    func handleOpenURL(url: URL)
    {
        wechatAuthStep.handleOpenURL(url)
    }
}

